package com.xxx.video.commen.utils;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.view.View;

import androidx.core.content.ContextCompat;

import com.xxx.video.R;
import com.xxx.video.VideoApplication;
import com.xxx.video.commen.adapters.BaseViewHolder;
import com.xxx.video.commen.beans.BaseBean;
import com.xxx.video.commen.configs.Constant;
import com.xxx.video.commen.configs.UserManager;
import com.xxx.video.commen.dbs.utils.DbUtils;
import com.xxx.video.commen.events.OpenPermissionEvent;
import com.xxx.video.commen.views.ProgressView;
import com.xxx.video.download.DownloadTask;
import com.xxx.video.download.StatusUtil;
import com.xxx.video.download.core.breakpoint.BreakpointInfo;
import com.xxx.video.login.activitys.LoginActivity;
import com.xxx.video.mine.activitys.DownloadManagementActivity;
import com.xxx.video.network.listeners.CommonResponseListener;
import com.xxx.video.network.utils.NetWorkUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;


public class DownloadUtils {
    private static DownloadUtils mDownloadUtils = null;
    /**
     * download all task
     */
    private HashMap<String, DownloadTask> mDownloadTaskHashMap = new HashMap<>();
    String[] permissions = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"
    };

    private DownloadUtils() {
    }

    public static DownloadUtils getInstance() {
        if (mDownloadUtils == null) {
            synchronized (DownloadUtils.class) {
                if (mDownloadUtils == null) {
                    mDownloadUtils = new DownloadUtils();
                }
            }
        }
        return mDownloadUtils;
    }

    /**
     * download url
     *
     * @param url url
     */
    public boolean download(String url, RecyclerviewDownloadListener downloadListener) {
        if (ContextCompat.checkSelfPermission(VideoApplication.getInstance(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            OpenPermissionEvent openPermissionEvent = new OpenPermissionEvent();
            openPermissionEvent.permissions = permissions;
            EventBus.getDefault().post(openPermissionEvent);
            ToastUtils.showError(StringUtils.getInstance().getString(R.string.tip_please_open_the_read_and_write_external_storage_permission));
            return false;
        }
        startDownload(url, downloadListener);
        return true;
    }

    private void startDownload(String url, RecyclerviewDownloadListener downloadListener) {
        L.d("downloadUrl", url);
        FileUtils.getInstance().checkLocalFilePath(Constant.DOWNLOAD_VIDEO_PATH);
        if (mDownloadTaskHashMap.get(url) == null) {
            DownloadTask downloadTask = createDownloadTask(url);
            /*
             * not have
             */
            downloadTask.enqueue(downloadListener);
            mDownloadTaskHashMap.put(url, downloadTask);
        } else {
            /*
             * have
             */
            mDownloadTaskHashMap.get(url).enqueue(downloadListener);
        }

    }

    /**
     * tet tas
     *
     * @param url url
     * @return task
     */
    private DownloadTask createDownloadTask(String url) {
        return new DownloadTask.Builder(url, new File(Constant.DOWNLOAD_VIDEO_PATH))
                .setFilename(getFileName(url))
                .setFilenameFromResponse(false)
                .setPassIfAlreadyCompleted(false)
                .setConnectionCount(3)
                .setPreAllocateLength(false)
                .setMinIntervalMillisCallbackProcess(1000)
                .setWifiRequired(false)
                .setAutoCallbackToUIThread(true)
                .build();
    }

    /**
     * get status
     *
     * @param url url
     * @return states
     */
    public StatusUtil.Status getStatus(String url) {
        StatusUtil.Status status = StatusUtil.getStatus(url, Constant.DOWNLOAD_VIDEO_PATH, getFileName(url));
        return status;
    }

    /**
     * fet file name
     *
     * @param url url
     * @return file name
     */
    public String getFileName(String url) {
        return url.replace(Constant.resBeforeUrl, "").replace("/", "");
    }

    /**
     * get info
     *
     * @param url url
     * @return info
     */
    public BreakpointInfo getDownloadInfo(String url) {
        return StatusUtil.getCurrentInfo(url, Constant.DOWNLOAD_VIDEO_PATH, getFileName(url));
    }

    /**
     * set status
     *
     * @param tvItemRankingListDownload view
     * @param url                       urk
     */
    public void setStatus(ProgressView tvItemRankingListDownload, String url, BaseViewHolder baseViewHolder) {
        StatusUtil.Status status = DownloadUtils.getInstance().getStatus(url);
        tvItemRankingListDownload.setVisibility(View.VISIBLE);
        switch (status) {
            case COMPLETED:
                tvItemRankingListDownload.setProgress(100);
                tvItemRankingListDownload.setVisibility(View.GONE);
                break;
            case RUNNING:
                BreakpointInfo breakpointInfo1 = DownloadUtils.getInstance().getDownloadInfo(url);
                if (breakpointInfo1 != null) {
                    final float percent = (float) breakpointInfo1.getTotalOffset() / breakpointInfo1.getTotalLength();
                    tvItemRankingListDownload.setProgress((int) (percent * 100));
                    if ((int) (percent * 100) == 100) {
                        tvItemRankingListDownload.setVisibility(View.GONE);
                    }
                }
                if (mDownloadTaskHashMap.get(url) != null) {
                    try {
                        RecyclerviewDownloadListener recyclerviewDownloadListener1 = (RecyclerviewDownloadListener) mDownloadTaskHashMap.get(url).getListener();
                        recyclerviewDownloadListener1.setBaseViewHolder(baseViewHolder);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case PENDING:
                break;
            case UNKNOWN:
            case IDLE:
            default:
                BreakpointInfo breakpointInfo2 = DownloadUtils.getInstance().getDownloadInfo(url);
                if (breakpointInfo2 != null) {
                    final float percent = (float) breakpointInfo2.getTotalOffset() / breakpointInfo2.getTotalLength();
                    tvItemRankingListDownload.setProgress((int) (percent * 100));
                    startDownload(url, new RecyclerviewDownloadListener(baseViewHolder));
                }
                break;
        }
    }

    public void startDownload(Context context, String videoUrl, String fId, String fTitle,
                              String fPicurl, String fCreateTime, int fPlayTimes, int fCommentTimes,int type) {
        /*
         * download
         */
        //if download .start download activity, ir download
        BreakpointInfo breakpointInfo = DownloadUtils.getInstance().getDownloadInfo(ResourcesUtils.getInstance().getDownloadPath(videoUrl));
        if (breakpointInfo == null) {
            if (UserManager.getInstance().isLogin()) {
                if (DownloadUtils.getInstance().download(ResourcesUtils.getInstance().getDownloadPath(videoUrl), new RecyclerviewDownloadListener(null))) {
                    DbUtils.getInstance().addDownloadHistoryBean(fId,
                            videoUrl,
                            fTitle,
                            fPicurl,
                            fCreateTime,
                            fPlayTimes,
                            fCommentTimes);
                    ToastUtils.showSuccess(StringUtils.getInstance().getString(R.string.tip_download_start));
                    downloadFollow(context, fId, type);
                }
            } else {
                downloadFollow(context, fId, type);
            }
        } else {
            Intent intent = new Intent(context, DownloadManagementActivity.class);
            context.startActivity(intent);
        }
    }

    public void downloadFollow(Context context, String videoId, int type) {
        if (!UserManager.getInstance().isLogin()) {
            Intent intent = new Intent(context, LoginActivity.class);
            context.startActivity(intent);
            return;
        }
        NetWorkUtils.getInstance().downloadFollow(videoId, String.valueOf(type), new CommonResponseListener<BaseBean>() {

            @Override
            public void onSuccess(BaseBean successOb, String result) {

            }

            @Override
            public void onFailure(Object failureObj) {

            }
        });
    }

}
